package com.asen.commons.core.jdbc.builder.mysql.filter;

import com.asen.commons.core.jdbc.param.SqlColumn;
import com.asen.commons.core.jdbc.param.SqlContextManager;
import com.asen.commons.core.meta.dao.FilterItem;
import com.asen.commons.core.meta.enums.FilterSymbolEnum;
import com.asen.commons.utils.StringUtils;

/**
 * Like过滤解析器
 *
 * @author Gary
 * @version 1.0
 * @date 2021-08-22
 */
public class LikeFilterParser implements FilterParser {

    @Override
    public CharSequence parse(SqlContextManager contextManager, FilterItem filterItem) {
        SqlColumn sqlColumn = contextManager.getSqlColumn(filterItem.getFieldName());
        if (sqlColumn == null) {
            return "";
        }

        String symbolName = filterItem.getSymbol().name();
        StringBuilder sql = new StringBuilder();
        if (FilterSymbolEnum.LIKE_IGNORE_CASE == filterItem.getSymbol()) {
            sql.append("upper(").append(sqlColumn.getFullColumn()).append(")");
        } else {
            sql.append(sqlColumn.getFullColumn());
        }
        sql.append(filterItem.getSymbol().getDesc());
        sql.append(" CONCAT(");
        if (!StringUtils.contains(symbolName, "LEFT")) {
            sql.append("'%',");
        }
        if (FilterSymbolEnum.LIKE_IGNORE_CASE == filterItem.getSymbol()) {
            sql.append("upper(?)");
        } else {
            sql.append("?");
        }
        if (!StringUtils.contains(symbolName, "RIGHT")) {
            sql.append(",'%'");
        }
        sql.append(")");
        contextManager.setParam(sqlColumn.getJavaType(), filterItem.getValue());
        return sql;
    }

}
